/*
 * @Author: lyztroy lyztroy@bupt.edu.cn
 * @Date: 2021-12-12 22:06:25
 * @LastEditors: lyztroy lyztroy@bupt.edu.cn
 * @LastEditTime: 2022-06-12 15:55:55
 * @FilePath: /visualNotes/src/modules/Diagram/components/toolbar.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React from "react";
import { useParams } from "react-router-dom";
import { db,payloads, SUCCESS_CODE} from "@/service";
import {  message as Message } from "antd";
import {  useSelector } from "react-redux";
import {  RootState } from "@/store";
import style from "./index.module.less";

interface IProps {
  instance: any;
}
const ToolBar = (props: IProps) => {
  var query=window.location.href;
  var toolID  = query.toString().slice(-8);
  const { type } = useParams<{
    diagramId?:string ;
    type: string;
  }>();
  const { reactFlowInstance } = useSelector(
    (state: RootState) => state.diagram
  );

  // 保存
  const handleSave = async () => {
    const payload={
      diagramId:toolID,
      type,
      elements: reactFlowInstance.toObject()?.elements,
    };
    const res=await db.collection("payloads")
    .where(
        {diagramId:toolID}
      ).field({
        type:true,
        elements:true,
        diagramId:true,
        _id:true,
      })
      .get()
    if(res.data[0]){
      const { code, message } = await payloads.updatePayload(payload);
      if (code === SUCCESS_CODE) {
        Message.success(`保存成功`);
      } else {
        Message.error(message);
      }
    }
    else{
      const { code, message } = await payloads.addPayload(payload);
      if (code === SUCCESS_CODE) {
        Message.success(`保存成功`);
      } else {
        Message.error(message);
      }
    }
  };

  const back = async () => {
    window.history.back()
  }
  return (
    
    <div className={style.toolContainer}>
      <button onClick={handleSave}>保存</button>
      <button onClick={back}>返回</button>
    </div>
  );
};
export default ToolBar;
